package svcauth

import (
	"net/http"
	"strings"

	"gitee.com/hexug/devcloud/mcenter/apps"
	"gitee.com/hexug/devcloud/mcenter/apps/token"
	"gitee.com/hexug/devcloud/mcenter/common/logger"
	"gitee.com/hexug/devcloud/mcenter/consted"
	"github.com/emicklei/go-restful/v3"
)

type ServerAuth struct {
	tok token.Server
}

func NewServerAuth() *ServerAuth {
	tk := apps.GetApp(token.AppName).(token.Server)
	return &ServerAuth{
		tok: tk,
	}
}

func (s *ServerAuth) HttpAuth(requset *restful.Request,
	response *restful.Response,
	next *restful.FilterChain) {
	router := requset.SelectedRoute()
	// fmt.Println(router.Metadata())
	//如果获取的auth是true，就执行认证
	if router.Metadata()["auth"] != nil && router.Metadata()["auth"].(bool) {
		headerKey := requset.HeaderParameter(consted.TOKEN_HEADER_KEY)
		tkSet := strings.Split(headerKey, " ")
		if len(tkSet) != 2 {
			response.WriteErrorString(http.StatusUnauthorized, "未携带合法令牌")
			return
		}
		username := tkSet[0]
		accessToken := tkSet[1]
		vtr := token.NewValidateTokenRequest(username)
		vtr.AccessToken = accessToken
		tk, err := s.tok.ValidateToken(requset.Request.Context(), vtr)
		if err != nil {
			logger.L().Error(err.Error())
			response.WriteErrorString(http.StatusUnauthorized, "令牌无效")
			return
		}
		requset.SetAttribute(consted.TOKEN_HEADER_KEY, tk)
	}

	next.ProcessFilter(requset, response)
}
